//
//  LKHomeViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/4/12.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKHomeViewController.h"
#import "LKHomeHeaderCell.h"
#import "YXCalendarView.h"
#import "LKDayInformationViewController.h"
#import "LKDayAssetsViewController.h"
#import "LKAllScheduleViewController.h"
#import "LKHomeNoticeViewController.h"
#import "LKScheduleListModel.h"
#import "LKDailyChartViewController.h"
#import "LKDailyChartTeamViewController.h"
#import "YLPushViewModel.h"
#import "LKChartsListViewController.h"
#import "LKYearViewController.h"
@interface LKHomeViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong)LKBaseTableview *tableview;
@property (nonatomic, strong) YXCalendarView *calendar;
@property(nonatomic,strong) UIImage *bluepot;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSMutableArray *bottomSchduleArray;
@property(nonatomic,copy)NSString *selectTimeStr;
@end

@implementation LKHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableview reloadData];
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerReloadData)];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bottomTableviewReload) name:tableviewReloadNotice object:nil];
    [self getAccountDetailInformation];
    [self getBottomCalendScheduleWithDateTime:[[[NSString getCurrentTime] componentsSeparatedByString:@" "] firstObject]];
//    [self getCalendTypeData];
//    [self getContainScheuldDay];
//     [LKUserInforTool noAccount];
    // Do any additional setup after loading the view.
}
-(void)headerReloadData{
    [self.tableview.mj_header endRefreshing];
    [self.tableview reloadRow:0 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
}
-(void)bottomTableviewReload{
    [self getBottomCalendScheduleWithDateTime:[[[NSString getCurrentTime] componentsSeparatedByString:@" "] firstObject]];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //设置导航条文字颜色 白色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:blueDefault}];
    self.tabBarController.tabBar.hidden = NO;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //设置导航条文字颜色 白色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:COLOR_HEX(0x000000)}];
}
-(void)setNavgationBackBtn{
    [super setNavgationBackBtn];
    self.navigationItem.title = @"首页";
    self.navigationItem.leftBarButtonItem = nil;
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"xiaoxi"] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        LKHomeNoticeViewController *vc = [[LKHomeNoticeViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }];
}

-(LKBaseTableview *)tableview{
    if (!_tableview) {
        _tableview = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT - TAB_BAR_HEIGHT) style:UITableViewStyleGrouped registercellClasss:@[@"LKHomeHeaderCell"]];
        [self.view addSubview:_tableview];
        _tableview.delegate = self;
        _tableview.dataSource = self;
    }
    return _tableview;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return 3;
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  section == 0 ? 1:self.bottomSchduleArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        LKHomeHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKHomeHeaderCell"];
        WS(weakSelf)
        cell.linkBlock = ^(NSString *url) {
            LKWebViewController *vc = [[LKWebViewController alloc] init];
            vc.url = url;
          [weakSelf.navigationController pushViewController:vc animated:YES];
        };
//        [cell.helpPushSubject subscribeNext:^(id  _Nullable x) {
//            LKWebViewController *vc = [[LKWebViewController alloc] init];
//            vc.url = x;
//          [weakSelf.navigationController pushViewController:vc animated:YES];
//        }];
        UITapGestureRecognizer *dayinforTap = [[UITapGestureRecognizer alloc] init];
        [dayinforTap.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            LKDayInformationViewController *vc = [[LKDayInformationViewController alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        [cell.dayInformatioView addGestureRecognizer:dayinforTap];
        UITapGestureRecognizer *assetsTap = [[UITapGestureRecognizer alloc] init];
        [assetsTap.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            LKDayAssetsViewController *vc = [[LKDayAssetsViewController alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        [cell.dayAssetsView addGestureRecognizer:assetsTap];
        
        UITapGestureRecognizer *dailyChartTap = [[UITapGestureRecognizer alloc] init];
        [dailyChartTap.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
//            LKChartsListViewController *vc = [[LKChartsListViewController alloc] init];
//            [self.navigationController pushViewController:vc animated:YES];
//            return ;
            LKUserInfor *userInfor = [LKUserInforTool account];
            if ([userInfor.isDeptLeader boolValue]) {
                LKDailyChartTeamViewController *vc = [[LKDailyChartTeamViewController alloc] init];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }else{
                LKDailyChartViewController *vc = [[LKDailyChartViewController alloc] init];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }
        }];
        [cell.dailyChartView addGestureRecognizer:dailyChartTap];
        return cell;
    }
    static NSString *cellId = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    cell.imageView.image = self.bluepot;
    LKScheduleListModel *model = self.bottomSchduleArray[indexPath.row];
    cell.textLabel.text = model.calenderName;
    cell.textLabel.textColor = cellTextColor;
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return indexPath.section == 0 ? ((WIDTH * 133 / 375) + 90) :55;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    if (section == 0) {
        return view;
    }
    return view;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    if (section == 1) {
        WS(weakSelf)
        LKBaseButton *btn = [LKBaseButton buttonWithFrame:CGRectZero type:UIButtonTypeCustom title:@"加载更多>>" titleColor:COLOR_HEX(0x4A78E8) layercorne:0 font:[UIFont systemFontOfSize:14] backgroudColor:[UIColor whiteColor] AndActionBlock:^(UIButton *btn) {
            LKAllScheduleViewController *vc = [[LKAllScheduleViewController alloc] init];
            vc.timeDateStr = weakSelf.selectTimeStr;
            [self.navigationController pushViewController:vc animated:YES];
        }];
        [view addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
        return view;
    }
    _calendar = [[YXCalendarView alloc] initWithFrame:CGRectMake(0, 12,WIDTH, 115) Date:[NSDate date] Type:CalendarType_Week];
    _calendar.backgroundColor = COLOR_HEX(0xF4F7F9);
    //    __weak typeof(_calendar) weakCalendar = _calendar;
    //    _calendar.refreshH = ^(CGFloat viewH) {
    //        [UIView animateWithDuration:0.3 animations:^{
    //            weakCalendar.frame = CGRectMake(0, 0, WIDTH, viewH);
    //        }];
    //
    //    };
    WS(weakSelf)
    _calendar.sendSelectDate = ^(NSDate *selDate) {
        NSString *dateStr = [[YXDateHelpObject manager] getStrFromDateFormat:@"yyyy-MM-dd" Date:selDate];
        weakSelf.selectTimeStr = dateStr;
        [weakSelf getBottomCalendScheduleWithDateTime:dateStr];
                NSLog(@"%@",dateStr);
    };
    [view addSubview:_calendar];
    view.backgroundColor = cellHeaderBgColor;
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return section == 0 ? 0.0000000001:115;
    return  0.0000000001;

}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    return section == 0 ? 12:40;
    return section == 0 ? 127:40;

}

#pragma mark 生成image
- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    
}
-(UIImage *)bluepot{
    if (!_bluepot) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 5)];
        view.backgroundColor = COLOR_HEX(0x3677F7);
        view.layer.cornerRadius = 2.5;
        view.layer.masksToBounds = YES;
        _bluepot = [self makeImageWithView:view withSize:CGSizeMake(5, 5)];
    }
    return _bluepot;
}

/**
 获取包含日程的时间
 */
-(void)getContainScheuldDay{
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:homeContainScheduleUrl header:[LKUserInforTool header] parameters:@{@"timeFrom":@"2018-05-10",@"timeTo":@"2018-05-25"} progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        
        
        
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}


///**
// 获取用户详情
// */
//-(void)getAccountDetailInformation{
//    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:UserDetailUrl header:[LKUserInforTool header] parameters:nil progress:^(NSProgress * _Nullable progress) {
//        
//    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
//        LKUserInfor *userInfor = [LKUserInfor accountWithDict:responseObject[@"result"]];
//        userInfor.token = [LKUserInforTool account].token;
//        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:userAccountCaculationUrl header:[LKUserInforTool header] parameters:nil progress:^(NSProgress * _Nullable progress) {
//            
//        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
//            NSString *customerCout = [NSString stringWithFormat:@"%@",responseObject[@"result"][@"cusertomerCount"]];
//            NSString *investMoney = [NSString stringWithFormat:@"%@",responseObject[@"result"][@"orderInverstment"]];
//            NSString *investFundMoney = [NSString stringWithFormat:@"%@",responseObject[@"result"][@"orderInverstmentFund"]];
//            userInfor.cusertomerCount = customerCout;
//            userInfor.orderInverstment = investMoney;
//            userInfor.orderInverstmentFund = investFundMoney;
//            [LKUserInforTool saveAccount:userInfor];
//        } failure:^(NSString * _Nullable errorMessage) {
//            
//        }];
//       
//        
//    } failure:^(NSString * _Nullable errorMessage) {
//    }];
//}

/**
 获取底部日程列表信息
 */
-(void)getBottomCalendScheduleWithDateTime:(NSString *)dateTime{
    [self.bottomSchduleArray removeAllObjects];
    NSDictionary *param = @{@"Number":@"5",@"EntryTime":dateTime};
    
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:homeAllScheduleUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        NSArray *array = responseObject[@"result"];
        for (NSDictionary *dic in array) {
            LKScheduleListModel *model = [LKScheduleListModel modelWithDictionary:dic];
            if (self.bottomSchduleArray.count >= 3) {
                break;
            }
            [self.bottomSchduleArray addObject:model];
        }
        [self.tableview reloadSection:1 withRowAnimation:UITableViewRowAnimationNone];
        
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
-(NSMutableArray *)bottomSchduleArray{
    if (!_bottomSchduleArray) {
        _bottomSchduleArray = [[NSMutableArray alloc] init];
    }
    return _bottomSchduleArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
